import axios from 'axios';
import config from '../Config/config';
import dayjs from 'dayjs';
import webUrl from '../Config/web';


//设置header头
const setHeader = function (){

    let token = getToken();

    if(!token){
        console.log('没有token');
        return {
            'X-Custom-Header': 'foobar'
        };
    }

    console.log('有token');

    return {
        'Accept': 'application/json',
        'Authorization':'Bearer '+token.access_token
    };
}


//保存token
export const saveToken = function(response){

    let data = response.data;

    let timestamp = dayjs().add(data.expires_in, 'second').toString();

    document.cookie = 'token_type='+data.token_type+';expires='+timestamp;
    document.cookie = 'access_token='+data.access_token+';expires='+timestamp;
    document.cookie = 'refresh_token='+data.refresh_token+';expires='+timestamp;

    console.log('token保存完毕');
}

//删除重复
const trim = function(str) {
    return str.replace(/^\s+|\s+$/g, "");
}

//读取token
const getToken = function(){
    let cookiesStr = document.cookie.split(";");

    let tokensObject = {};

    cookiesStr.map((value, index)=>{
        let values = value.split('=');
        
        let key = trim(values[0]);

        //只要跟token有关的cookie
        if(key==='token_type' || key==='access_token' || key==='refresh_token'){
            tokensObject[trim(values[0])] = values[1];
        }

    });

    for(let key in tokensObject){
        return tokensObject;
    }

    return false;
}


//创建axios对象
export let http = axios.create({
    // baseURL:config.base_url,
    timeout:config.time_out,
    headers:setHeader()
});

//刷新http对象
export let reflashHttp = function(){
    http = axios.create({
        // baseURL:config.base_url,
        timeout:config.time_out,
        headers:setHeader()
    });
}

//登录 todo:重构职责单一
export const login = function(username, password, successAction, errorAction){
    http.post(webUrl.login, {
        username:username,
        password:password,
        client_id:config.client_id,
        client_secret:config.client_secret,
        scope:'',
        grant_type:'password'
    })
    .then(function(response){
        
        saveToken(response);

        reflashHttp();

        successAction(response);

    }).catch(function(error){

        errorAction(error);
    });
}

//请求
export const request = function(method, url, params, successAction, errorAction, data){
    http.request({
        url:url,
        method:method,
        params:params,
        data:data
    }).then(function(response){
        successAction(response);
    }).catch(function(error){
        errorAction(error);
    })
}

//get请求
export const get = function(url, params, successAction, errorAction){
    request('get', url, params, successAction, errorAction);
}

//post请求
export const post = function(url, params, successAction, errorAction){
    request('post', url, {}, successAction, errorAction, params);
}